package com.yixinsoft.basic.service.manage.system;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yixinsoft.basic.mapper.manage.system.UserMapper;
import com.yixinsoft.basic.model.manage.system.User;
import com.yixinsoft.basic.service.base.BaseService;
import com.yixinsoft.basic.service.base.PasswordHelper;

/**
 * Created by hqy on 2016/06/05
 */
@Service
public class UserService extends BaseService<User> {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private PasswordHelper passwordHelper;
	
	/**
	 * 根据用户名查找用户
	 * @param username
	 * @return
	 */
	public User findByUsername(String username) {
		return userMapper.findByUsername(username); 
	}
	
	public PageInfo<User> queryListPage(User user, Integer page, Integer rows) {
		PageHelper.startPage(page, rows);
		List<User> list = userMapper.queryListPage(user);
		return new PageInfo<>(list);
	}
	
	/**
	 * 保存用户
	 */
	public Integer save(User user) {
		passwordHelper.encryptPassword(user);
		return userMapper.insert(user);
	}
	
	/**
	 * 修改密码
	 * @param userId
	 * @param newPassword
	 */
	public void changePassword(Long userId, String newPassword) {
		User user = queryById(userId);
		user.setPassword(newPassword);
		//加密
		passwordHelper.encryptPassword(user);
		
		userMapper.updateByPrimaryKeySelective(user);
	}
	
	/**
	 * 启用或停用
	 * @param ids
	 */
	public List<User> updateState(Long[] ids, Boolean state) {
		List<User> users = new ArrayList<>();
		for (Long id : ids) {
			User user = queryById(id);
			user.setLocked(state);
			userMapper.updateByPrimaryKeySelective(user);
			users.add(user);
		}
		return users;
	}
	
	/**
     * 根据用户名查找其角色
     * @param username
     * @return
     */
    @SuppressWarnings("unchecked")
	public Set<String> findRoles(String username) {
    	User user = userMapper.findByUsername(username);
    	if(user == null) {
            return Collections.EMPTY_SET;
        }
    	return roleService.findRoles(user.getRoles().toArray(new Long[0]));
    }
    
    /**
     * 根据用户名查找其权限
     * @param username
     * @return
     */
    @SuppressWarnings("unchecked")
	public Set<String> findPermissions(String username) {
    	User user = userMapper.findByUsername(username);
    	if(user == null) {
            return Collections.EMPTY_SET;
        }
    	return roleService.findPermissions(user.getRoles().toArray(new Long[0]));
    }
}
